//切换学校选择页
import React, {Component} from 'react'
import {View, Text, ScrollView, Image, TouchableOpacity, TouchableWithoutFeedback, Alert} from 'react-native'
import styles from '../../configs/styles'
import {UserLogin} from '../../configs/api'
import Icon from 'react-native-vector-icons/Ionicons'
import Helper from '../../helpers'
class ChangeSchool extends Component {
  static navigationOptions = ({navigation}) => {
    return {
      title: '切换登录学校'
    }
  };

  //初始化props和state
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  doChangeSchool = (school_id)=>{
    if(loginState.school_id==school_id){
      return null
    }else{
      UserLogin(loginState.username, loginState.password, school_id).then(res=>{
        if(res.token && res.user_id){
          const data = {
            school_id: res.school_id,
            token: res.token,
            user_id: res.user_id,
            username: loginState.username,
            password: loginState.password,
            info: res.info
          }
          storage.save({
            key: 'loginState',  // 注意:请不要在key中使用_下划线符号!
            data: data
          })
          Object.assign(loginState, data)
          App.refreshLogin(res.school_id)
        }else{
          Alert.alert(res.msg)
        }
      }).catch(err =>{
        Alert.alert('服务器错误！')
        console.log(err)
      })
      this.props.navigation.goBack()
    }

  }

  _render_item = (arr)=>{
    return (
      <TouchableOpacity  key={arr[1]} onPress={()=>this.doChangeSchool(arr[1])}
                         style={{flexDirection: 'row', alignItems: 'flex-start', padding: 20, borderBottomWidth: 1, borderColor: 'lightgrey'}}>
        <Text style={arr[1]==loginState.school_id?styles.text_black:styles.text_blue}>{arr[0]}</Text>
        <View style={{alignItems: 'flex-end', flex: 1}}>
          <Icon name={'ios-arrow-forward'} size={20} style={[styles.apply_info_text, {}]}/>
        </View>
      </TouchableOpacity>
    )
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        {loginState.info.all_schools.map((a)=>this._render_item(a))}
      </View>
    )
  }

}

export default ChangeSchool